package com.swang.pms.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.swang.pms.model.vo.ResultMessage;

/**
 * @ClassName: TokenCheckInterceptor
 * @Description: TODO
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
public class TokenCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (httpServletRequest.getHeader("x-requested-with") != null
                && "XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("x-requested-with"))) {//判断是否为ajax请求
            if (!httpServletRequest.getRequestURI().contains("listLeftMenu")) {//医院平台一级菜单的点击跳转也是通过ajax请求完成，过滤这部分请求
                HttpSession session = httpServletRequest.getSession();
                Long tokenTime = (Long) session.getAttribute("tokenTime");
                Long nowTime = System.currentTimeMillis();
                if (tokenTime == null) {
                    session.setAttribute("tokenTime", nowTime);
                    return true;
                }
                if ((nowTime - tokenTime) > 10000) {
                    return true;
                }
                ResultMessage resultMessage = new ResultMessage();
                resultMessage.setResult(false);
                resultMessage.setErrorMessage("数据正在处理中，请勿重复操作！");
                resultMessage.setMessage("数据正在处理中，请勿重复操作！");
                JSONObject json = (JSONObject) JSONObject.toJSON(resultMessage);
                httpServletResponse.getWriter().println(json);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView)
            throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
            throws Exception {
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("tokenTime");
    }
}
